package com.taxshare.manager.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.manager.constant.ResultConstant;
import com.taxshare.manager.constant.UserConstant;
import com.taxshare.manager.entity.UserEntity;
import com.taxshare.manager.entity.UserRoleEntity;
import com.taxshare.manager.mapper.UserMapper;
import com.taxshare.manager.mapper.UserRoleMapper;
import com.taxshare.manager.view.dto.UserDTO;
import com.taxshare.manager.view.dto.UserRoleDTO;
import com.taxshare.manager.view.vo.UserVO;
import com.taxshare.mybatis.pager.PageInfoRequest;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.mybatis.utils.DozerBeanUtil;
import com.taxshare.response.beans.Response;
import com.taxshare.tools.constant.CommonConstant;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.UUIDUitl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @ClassName: UserService
 * @Description:
 * @author: luozhongyi
 * @date: 2021/1/29 14:15
 */
@Service
public class UserService extends ServiceImpl<UserMapper, UserEntity> {

    @Autowired
    UserRoleMapper roleMapper;

    /**
     * 新增用户
     *
     * @param userDTO
     * @return
     */
    public Response add(UserDTO userDTO) throws NoSuchAlgorithmException {
        String userType = UserConstant.USER_TYPE_1;
        if (StrUtil.hasBlank(userDTO.getUserLoginName())) {
            return Response.error(ResultConstant.RET_U0001_CODE, ResultConstant.RET_U0001_MSG);
        }
        if (StrUtil.hasBlank(userDTO.getUserPassword())) {
            return Response.error(ResultConstant.RET_U0002_CODE, ResultConstant.RET_U0002_MSG);
        }
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_login_name", userDTO.getUserLoginName());
        if (baseMapper.selectCount(queryWrapper) > 0) {
            return Response.error(ResultConstant.RET_U0000_CODE, ResultConstant.RET_U0000_MSG);
        }
        if (UserConstant.USER_TYPE_3.equals(UserInfoUtil.getUserType())) {
            userType = UserConstant.USER_TYPE_2;
        }
        UserEntity entity = DozerBeanUtil.map(userDTO, UserEntity.class);
        entity.setUserId(UUIDUitl.UUID32(false));
        entity.setUserPassword(userDTO.getUserPassword());
        entity.setUserType(userType);
        entity.setUserState(UserConstant.USER_STATE_1);
        this.save(entity);
        return Response.success();
    }

    /**
     * 编辑用户
     *
     * @param userDTO
     * @return
     */
    public Response edit(UserDTO userDTO) {
        if (StrUtil.hasBlank(userDTO.getUserLoginName())) {
            return Response.error(ResultConstant.RET_U0001_CODE, ResultConstant.RET_U0001_MSG);
        }
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_login_name", userDTO.getUserLoginName());
        queryWrapper.ne("user_id", userDTO.getUserId());
        queryWrapper.eq("tenant_id", UserInfoUtil.getTenantId());
        if (baseMapper.selectCount(queryWrapper) > 0) {
            return Response.error(ResultConstant.RET_R0002_CODE, ResultConstant.RET_R0002_MSG);
        }
        UserEntity entity = DozerBeanUtil.map(userDTO, UserEntity.class);
        return Response.success(this.updateById(entity));
    }

    /**
     * 删除用户
     *
     * @param userDTO
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public Response delete(UserDTO userDTO) {
        QueryWrapper<UserEntity> userWrapper = new QueryWrapper();
        userWrapper.eq("user_id", userDTO.getUserId());
        baseMapper.delete(userWrapper);

        QueryWrapper<UserRoleEntity> userRoleWrapper = new QueryWrapper();
        userRoleWrapper.eq("user_id", userDTO.getUserId());
        roleMapper.delete(userRoleWrapper);
        return Response.success();
    }

    /**
     * 查询用户
     *
     * @param query
     * @return
     */
    public Response info(PageRequest<UserDTO> query) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper();
        UserDTO userDTO = query.getInfo();
        PageInfoRequest pageInfoRequest = query.getPage();
        if (!StrUtil.hasBlank(userDTO.getUserLoginName())) {
            queryWrapper.like("user_login_name", userDTO.getUserLoginName());
        }
        if (!StrUtil.hasBlank(userDTO.getUserNickName())) {
            queryWrapper.like("user_nick_name", userDTO.getUserNickName());
        }
        if (!StrUtil.hasBlank(userDTO.getUserState())) {
            queryWrapper.eq("user_state", userDTO.getUserState());
        }
        //如果用户是普通用户就只能看自己新增的用户
        if (CommonConstant.AUTH_TYPE_1.equals(UserInfoUtil.getUserType())) {
            queryWrapper.eq("t.create_userid", UserInfoUtil.getUserID());
        }
        //用户查询排除管理员
        queryWrapper.notIn("user_type", Arrays.asList(CommonConstant.AUTH_TYPE_3));
        queryWrapper.orderByDesc("t.create_time");
        IPage<UserVO> result = baseMapper.queryUserInfos(new Page<>(pageInfoRequest.getCurrentPage(), pageInfoRequest.getPageSize()), queryWrapper);
        //页面根据用户类型控制按钮权限
        Map<String,Object> userMap = new HashMap<>();
        userMap.put("list",result);
        userMap.put("userType",UserInfoUtil.getUserType());
        return Response.success(userMap);
    }


    /**
     * 更改用户状态
     *
     * @param userDTO
     * @return
     */
    public Response updateState(UserDTO userDTO) {
        UserEntity entity = DozerBeanUtil.map(userDTO, UserEntity.class);
        return Response.success(this.updateById(entity));
    }

    /**
     * 重置密码
     *
     * @param userDTO
     * @return
     */
    public Response resetPassword(UserDTO userDTO) throws NoSuchAlgorithmException {
        UpdateWrapper<UserEntity> userWrapper = new UpdateWrapper();
        userWrapper.eq("user_id", userDTO.getUserId());
        UserEntity userEntity = new UserEntity();
        userEntity.setUserPassword(MD5.create().digestHex(UserConstant.USER_DEFAULT_PASSWORD));
        this.update(userEntity, userWrapper);
        return Response.success();
    }

    /**
     * 根据登录名查询用户
     *
     * @param userLoginName
     */
    public UserEntity findByUserLoginName(String userLoginName) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_login_name", userLoginName);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据用户ID查询角色
     *
     * @param userId
     * @return
     */
    public UserRoleEntity findRoleByUserId(String userId) {
        QueryWrapper<UserRoleEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        return roleMapper.selectOne(queryWrapper);
    }

    /**
     * 批量绑定用户角色
     *
     * @param userRoleDTO
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public Response batchBindRole(UserRoleDTO userRoleDTO) {
        //构造参数
        List<UserRoleDTO> urs = new ArrayList<>();
        UserRoleDTO dto;
        for (String userId : userRoleDTO.getUserIds()) {
            dto = new UserRoleDTO();
            dto.setRoleId(userRoleDTO.getRoleId());
            dto.setUserId(userId);
            urs.add(dto);
        }
        //先批量删除用户的角色信息
        roleMapper.deleteUserRoleBatch(urs);
        //批量保存用户角色信息
        roleMapper.insertUserRoleBatch(urs);
        return Response.success();
    }

    /**
     * 查询全部用户
     *
     * @return
     */
    public Response allInfo() {
        return Response.success(baseMapper.selectList(new QueryWrapper()));
    }

    /**
     * 查询当前用户
     *
     * @return
     */
    public Response userInfo() {
        UserVO vo = new UserVO();
        vo.setUserId(UserInfoUtil.getUserID());
        vo.setUserLoginName(UserInfoUtil.getUserLoginName());
        vo.setUserNickName(UserInfoUtil.getUserNickName());
        return Response.success(vo);
    }

    /**
     * 修改密码
     *
     * @return
     */
    public Response editPassword(UserDTO vo) {
        UserEntity entity=new UserEntity();
        entity.setUserId(vo.getUserId());
        entity.setUserPassword(vo.getUserPassword());
        baseMapper.updateById(entity);
        return Response.success();
    }

    /**
     * 查询用户id
     * @param loginName
     * @return
     */
    public Response getInfo(String loginName) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_login_name",loginName);
        UserEntity one = this.getOne(queryWrapper);
        if(one!=null){
            return Response.success(one.getUserId());
        }
        return Response.error("U001","该用户不存在");
    }
}
